package com.ls.demo.tcp.namespace;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.PlatformDependent;

import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;

/**
 * 用与存放连接
 * @author liShan
 * @date 2019/8/30 10:24
 */
public class Namespaces {

    private ConcurrentMap<String, ChannelHandlerContext> namespacesMap = PlatformDependent.newConcurrentHashMap();
    private ConcurrentMap<String, String> boxChannelMap = PlatformDependent.newConcurrentHashMap();
    private ConcurrentMap<String, String> channelBoxMap = PlatformDependent.newConcurrentHashMap();
    private volatile static Namespaces namespaces;

    private Namespaces(){}

    /**
     * 根据UUID获取客户端连接
     * @param uuid UUID
     * @return 客户端连接
     */
    public ChannelHandlerContext getClient(UUID uuid){
        return namespacesMap.get(uuid.toString());
    }

    /**
     * 根据UUID储存客户端连接
     * @param uuid UUID
     * @param channel   客户端连接
     */
    public void setClient(UUID uuid, ChannelHandlerContext channel){
        namespacesMap.put(uuid.toString(), channel);
    }

    /**
     * 根据UUID移除客户端连接
     * @param uuid UUID
     */
    public void removeClient(UUID uuid){
        namespacesMap.remove(uuid.toString());
        if (channelBoxMap.containsKey(uuid.toString())){
            boxChannelMap.remove(channelBoxMap.get(uuid.toString()));
            channelBoxMap.remove(uuid.toString());
        }
    }

    /**
     * 获取所有的客户端连接
     * @return 客户端连接
     */
    public Iterator<ChannelHandlerContext> getClients(){
        return namespacesMap.values().iterator();
    }

    /**
     * 获取总数量
     * @return 总数量
     */
    public int size(){
        return namespacesMap.size();
    }

    /**
     * 根据盒子的uuid获取该盒子的连接通道
     * @param boxUuid 盒子的uuid
     * @return 盒子的连接通道
     */
    public ChannelHandlerContext getChannel(String boxUuid){
        if (boxChannelMap.containsKey(boxUuid)){
            return namespacesMap.get(boxChannelMap.get(boxUuid));
        }
        return null;
    }

    /**
     * 根据连接通道的uuid获取该盒子uuid
     * @param channelUuid 连接通道的uuid
     * @return 盒子的uuid
     */
    public String getBoxUuid(String channelUuid){
        return this.channelBoxMap.get(channelUuid);
    }

    /**
     * 添加通道uuid和盒子的uuid的对应关系
     * @param boxUuid 盒子的uuid
     * @param channelUuid 通道的uuid
     */
    public void addBoxChannel(String boxUuid, String channelUuid){
        boxChannelMap.put(boxUuid, channelUuid);
        channelBoxMap.put(channelUuid, boxUuid);
    }

    /**
     * 获取该对象的实例
     * @return 对象的实例
     */
    public static Namespaces getInstance(){
        if (null == namespaces){
            synchronized (Namespaces.class){
                if (null == namespaces){
                    namespaces = new Namespaces();
                }
            }
        }
        return namespaces;
    }

}
